package com.grf.rocketmq;

import java.io.UnsupportedEncodingException;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import lombok.extern.slf4j.Slf4j;

/**
 * @author : guorf
 * @version : v1.0
 * @description : TODO push消息
 * @createTime : 2023/9/13 10:17
 */
@Slf4j
public class PushConsumer {
    public static void main(String[] args) throws MQClientException {
        // 初始化consumer，并设置consumer group name
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(ProducerUtil.GROUP_NAME);

        // 设置NameServer地址
        consumer.setNamesrvAddr(ProducerUtil.NAMESRV_ADDR);
        //订阅一个或多个topic，并指定tag过滤条件，这里指定*表示接收所有tag的消息
        consumer.subscribe(ProducerUtil.TOPIC, "*");
        //注册回调接口来处理从Broker中收到的消息
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            // 返回消费状态
            for (MessageExt msg: msgs) {
                try {
                    log.info("topic is: {}, tags is:{}, queue is: {}, body is: {}, property is: {}", msg.getTopic(), msg.getTags(), msg.getQueueId(), new String(msg.getBody(),"UTF-8"), msg.getUserProperty("user"));
//                    log.info("msg is: {}", msg);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
//                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
            // 返回消息消费状态，ConsumeConcurrentlyStatus.CONSUME_SUCCESS为消费成功
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });
        // 启动Consumer
        consumer.start();
        log.info("Consumer Started.");
    }
}
